﻿using System;
using System.Collections.Generic; 
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
/// <summary>
/// Summary description for RegistrationData
/// </summary>
public class RegistrationData
{
	SqlCommand cmd = null;
    SqlDataReader rd = null;
    DataSet ds = null;
    SqlDataAdapter da = null;
    MD5 md5 = null;


    DbCommand cm = null;
    SqlDatabase db = null;

    private static Random _random = new Random();

    public static T NumToEnum<T>(int number)
    {
        return (T)Enum.ToObject(typeof(T), number);
    }
   
    public RegistrationData()
	{
        System.Data.SqlClient.SqlConnection.ClearAllPools();
	}
    string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDev"].ToString();

    public static SqlConnection ConnectionOpen()
    {
        SqlConnection cn = null;
        cn = new SqlConnection();
        cn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDev"].ConnectionString;
        cn.Open();
        return cn;
    }

    #region private variables

    private string _fName = string.Empty;
    private string _lName = string.Empty;
    private string _dob = string.Empty;
    private string _email = string.Empty;
    private string _pwd = string.Empty;
    private string _salt = string.Empty;
    private string _usrname = string.Empty;
    private int _userId = 0;
    private int _usertypeid = 0;
    private int _groupid = 0;
    private string _add = string.Empty; 
    string _profileimage = string.Empty;
    #endregion

    #region public properties

    public string FirstName
    {
        get { return _fName; }
        set { _fName = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value); }
    }
    public string LastName
    {
        get { return _lName; }
        set { _lName = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value); }
    }
    public string DOB { get { return _dob; } set { _dob = value; } }
    public string Address { get { return _add; } set { _add = value; } }
    public string Email
    {
        get { return _email; }
        set { _email = value; }
    }
    public string Password
    {
        get { return _pwd; }
        set { _pwd = value; }
    }
    public string Salt
    {
        get { return _salt; }
        set { _salt = value; }
    }
    public string UserName { set { _usrname = value; } get { return _usrname; } }
    public int UserID  {  get { return _userId; }  set { _userId = value; }
    }
    public int UserTypeID { set { _usertypeid = value; } get { return _usertypeid; } }
    public Int64 MobileNo { get; set; }
    public Int16 UnivID { get; set; }
    public int CollegeID { get; set; }
    public string otherCollegeName { get; set; }
    public bool IsMobileDisclosed { get; set; }

    public HttpPostedFile UserImage { get; set; }
     

    public Int16 PassingYear { get; set; }

    public int GroupID { set { _groupid = value; } get { return _groupid; } }

    int _isacntactive = 0;
    public int IsAccountActive { set { _isacntactive = value; } get { return _isacntactive; } }
    public string ProfileImage { set { _profileimage = value; } get { return _profileimage; } }
    public byte DeptID { get; set; }//Used in kendo
    #endregion


    public enum UserType
    {
        Admin = 1,
        User = 2,
        Reviewer = 3,
        SysAdmin=4
    }


    public DataSet InsertRegistrationDetails()
    {
        ds = new DataSet();
        try
        {
            db = new SqlDatabase(conStr);
            using (cm = db.GetStoredProcCommand("Reg.Insert_RegistrationData"))
            {
                db.AddInParameter(cm, "@FirstName", DbType.String, this.FirstName);
                db.AddInParameter(cm, "@LastName", DbType.String, this.LastName);
                db.AddInParameter(cm, "@Email", DbType.String, this.Email);
                db.AddInParameter(cm, "@UserName", DbType.String, this.UserName);
                db.AddInParameter(cm, "@Password", DbType.String, this.Password);
                db.AddInParameter(cm, "@UnivID", DbType.Int16, this.UnivID);
                db.AddInParameter(cm, "@CollegeID", DbType.Int16, this.CollegeID);
                db.AddInParameter(cm, "@CollegeName", DbType.String, this.otherCollegeName);
                db.AddInParameter(cm, "@MobileNo", DbType.Int64, this.MobileNo);
                db.AddInParameter(cm, "@IsMobileDisclosed", DbType.Boolean, this.IsMobileDisclosed);
                db.AddInParameter(cm, "@Salt", DbType.String, this.Salt);
                db.LoadDataSet(cm, ds, "tbl");
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        return ds;
    }
 

    public DataSet GetRegistrationDetails(string Email)
    {
        DataSet ds = null;
        using (ds = new DataSet())
        {
            using (cmd = new SqlCommand("Reg.Get_RegistrationData"))
            {
                using (SqlConnection cn = ConnectionOpen())
                {
                    cmd.Connection = cn;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandTimeout = 0;

                    SqlParameter sEmail = new SqlParameter("@Email", SqlDbType.VarChar);
                    sEmail.Value = Email;
                    cmd.Parameters.Add(sEmail);

                    using (da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds);
                    }
                }
            }
        }
        return ds;
    }


    public DataSet Update_RegistrationDetails()
    {
        ds = new DataSet();
      string  FileName = string.Empty;
        int nFileLen = 0;
        byte[] FileBuffer = null;
        string FileExt = string.Empty;
        if (this.UserImage != null)
        {
            if (this.UserImage.ContentLength > 0)
            {
                FileName = System.IO.Path.GetFileName(this.UserImage.FileName);
                nFileLen = this.UserImage.ContentLength;
                FileExt = this.UserImage.ContentType;
                System.IO.Stream objStream = this.UserImage.InputStream;
                FileBuffer = new byte[nFileLen];
                objStream.Read(FileBuffer, 0, nFileLen);
            }
        }
        try
        {
            db = new SqlDatabase(conStr);
            using (cm = db.GetStoredProcCommand("Reg.Update_RegistrationData"))
            {
                db.AddInParameter(cm, "@UserID", DbType.Int32, this.UserID);
                db.AddInParameter(cm, "@FirstName", DbType.String, this.FirstName);
                db.AddInParameter(cm, "@LastName", DbType.String, this.LastName); 
                db.AddInParameter(cm, "@UnivID", DbType.Int16, this.UnivID);
                db.AddInParameter(cm, "@CollegeID", DbType.Int16, this.CollegeID);
                db.AddInParameter(cm, "@CollegeName", DbType.String, this.otherCollegeName);
                db.AddInParameter(cm, "@MobileNo", DbType.Int64, this.MobileNo);
                db.AddInParameter(cm, "@IsMobileDisclosed", DbType.Boolean, this.IsMobileDisclosed);
                if (FileName != string.Empty)
                {
                    db.AddInParameter(cm, "@UserImage", DbType.Binary, FileBuffer);
                    db.AddInParameter(cm, "@ImageName", DbType.String, FileName);
                }
                db.LoadDataSet(cm, ds, "tbl");
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        return ds;
    }

    public SqlDataReader CheckEmail(string Email)
    {
        SqlConnection cn = ConnectionOpen();
        cmd = new SqlCommand("Reg.CheckEmail", cn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandTimeout = 0;
        cmd.Connection = cn;

        SqlParameter sEMailID = new SqlParameter("@Email", SqlDbType.VarChar);
        sEMailID.Value = Email;
        cmd.Parameters.Add(sEMailID);

        rd = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        return rd;

    }

    public SqlDataReader CheckUserName(string UserName)
    {
        SqlConnection cn = ConnectionOpen();
        cmd = new SqlCommand("Reg.CheckUserName", cn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandTimeout = 0;
        cmd.Connection = cn;

        SqlParameter sUserName = new SqlParameter("@UserName", SqlDbType.VarChar);
        sUserName.Value = UserName;
        cmd.Parameters.Add(sUserName);

        rd = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        return rd;

    }


    public SqlDataReader CheckMobileNo()
    {
        SqlConnection cn = ConnectionOpen();
        cmd = new SqlCommand("Reg.CheckMobileNo", cn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandTimeout = 0;
        cmd.Connection = cn;

        SqlParameter sMobileNo = new SqlParameter("@MobileNo", SqlDbType.BigInt);
        sMobileNo.Value = this.MobileNo;
        cmd.Parameters.Add(sMobileNo);

        rd = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        return rd;

    }

    public DataSet GetUserEmailID(string Email)
    {
        DataSet ds = null;
        using (ds = new DataSet())
        {
            using (cmd = new SqlCommand("Reg.Select_UserEmailID"))
            {
                using (SqlConnection cn = ConnectionOpen())
                {
                    cmd.Connection = cn;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandTimeout = 0;

                    SqlParameter sEmail = new SqlParameter("@Email", SqlDbType.VarChar);
                    sEmail.Value = Email;
                    cmd.Parameters.Add(sEmail);

                    using (da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds);
                    }
                }
            }
        }
        return ds;
    }

    public bool ValidateCurrentUser(string inputPwd, string salt)
    {
        bool validated = false;
        md5 = MD5.Create();
        byte[] byteOPwd;
        byte[] byteOHash;

        byteOPwd = System.Text.Encoding.UTF8.GetBytes(this.Password + salt);//Decrypt Pwd
        byteOHash = md5.ComputeHash(byteOPwd);

        string sOPwd = ByteArrayToString(byteOHash);
        if (inputPwd.ToLower().Equals(sOPwd.ToLower()))
        {
            validated = true;
        }
        else
        {
            throw new System.Exception("Invalid User Name or Password !");
        }
        return validated;
    }

    private string ByteArrayToString(byte[] arrInput)
    {
        int i;
        System.Text.StringBuilder sOutput = new System.Text.StringBuilder(arrInput.Length);
        for (i = 0; i < arrInput.Length; i++)
        {
            sOutput.Append(arrInput[i].ToString("X2"));
        }
        return sOutput.ToString();
    }
 

    public void Update_ProfileImage()
    {
        using (SqlCommand cmd = new SqlCommand("Reg.Update_ProfileImage"))
        {
            using (SqlConnection cn = ConnectionOpen())
            {
                cmd.Connection = cn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandTimeout = 0;

                SqlParameter sProfileImage = new SqlParameter("@ProfileImage", SqlDbType.VarChar);
                sProfileImage.Value = this.ProfileImage;
                cmd.Parameters.Add(sProfileImage);


                SqlParameter sUserID = new SqlParameter("@UserID", SqlDbType.Int);
                sUserID.Value = this.UserID;
                cmd.Parameters.Add(sUserID);
                cmd.ExecuteNonQuery();
            }
        }
    }
     
    //Making Encrypted Password
    public string protectpassword(string newpass)
    {
        Byte[] clearbytes = new UnicodeEncoding().GetBytes(newpass);
        Byte[] hashedpass = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearbytes);
        return BitConverter.ToString(hashedpass);     // Send the passsowrd to this method and see that it converts this into a encrypted password.

    }

    //generating random string
    public string RandomString(int size)
    {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < size; i++)
        {
            builder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * _random.NextDouble() + 65))));
        }
        return builder.ToString();

    }

    public SqlDataReader SelectUserDetails_Email(string Email)
    {
        SqlConnection cn = ConnectionOpen();
        cmd = new SqlCommand("Reg.SelectUserDetails_Email", cn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandTimeout = 0;
        cmd.Connection = cn;

        SqlParameter sEMailID = new SqlParameter("@Email", SqlDbType.VarChar);
        sEMailID.Value = Email;
        cmd.Parameters.Add(sEMailID);

        rd = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        return rd;

    }

    public DataSet SelectUserLoginDetails(string Email, string Password)
    {
        DataSet ds = null;
        using (ds = new DataSet())
        {
            using (cmd = new SqlCommand("Reg.Select_UserLoginDetails"))
            {
                using (SqlConnection cn = ConnectionOpen())
                {
                    cmd.Connection = cn;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandTimeout = 0;

                    SqlParameter sEmail = new SqlParameter("@Email", SqlDbType.VarChar);
                    SqlParameter sPassword = new SqlParameter("@Password", SqlDbType.VarChar);
                    sEmail.Value = Email;
                    sPassword.Value = Password;
                    cmd.Parameters.Add(sEmail);
                    cmd.Parameters.Add(sPassword);

                    using (da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds);
                    }
                }
            }
        }
        return ds;
    }
    //end of code for randam string

     public bool UpdateUserMaster_IsForgotPassword(string EmailID, string ForgotPasswordLink)
    {
        bool dataInserted = false;
        using (SqlCommand cmd = new SqlCommand("Reg.Update_Registration_IsForgotPassword"))
        {
            using (SqlConnection cn = ConnectionOpen())
            {
                cmd.Connection = cn;
                cmd.CommandTimeout = 0;
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter spEMailid = new SqlParameter("@Email", SqlDbType.VarChar);
                SqlParameter spForgotPasswordLink = new SqlParameter("@ForgotPasswordLink", SqlDbType.VarChar);
                spEMailid.Value = EmailID;
                spForgotPasswordLink.Value = ForgotPasswordLink;
                cmd.Parameters.Add(spEMailid);
                cmd.Parameters.Add(spForgotPasswordLink);
                if (cmd.ExecuteNonQuery() > 0)
                    dataInserted = true;
            }
        }
        return dataInserted;
    }

     public bool Update_EmailVerificationLink(int UserID, string Link)
     {
         bool dataInserted = false;
         using (SqlCommand cmd = new SqlCommand("Reg.Update_EmailVerificationLink"))
         {
             using (SqlConnection cn = ConnectionOpen())
             {
                 cmd.Connection = cn;
                 cmd.CommandTimeout = 0;
                 cmd.CommandType = CommandType.StoredProcedure;



                 SqlParameter sUserID = new SqlParameter("@UserID", SqlDbType.Int);
                 sUserID.Value = UserID;
                 cmd.Parameters.Add(sUserID);


                 SqlParameter sLink= new SqlParameter("@Link", SqlDbType.VarChar);
                 sLink.Value = Link;
                 cmd.Parameters.Add(sLink);
                 if (cmd.ExecuteNonQuery() > 0)
                     dataInserted = true;
             }
         }
         return dataInserted;
     }

    public DataSet SelectUserMaster_ForgotPasswordLink(string id)
    {
        DataSet ds = null;
        SqlDataAdapter da = null;
        SqlCommand cmd = null;
        using (cmd = new SqlCommand("Reg.Select_Registration_ForgotPasswordLink"))
        {
            using (ds = new DataSet())
            {
                using (SqlConnection cn = ConnectionOpen())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandTimeout = 0;

                    SqlParameter spForgotPasswordLink = new SqlParameter("@ForgotPasswordLink", SqlDbType.VarChar);
                    spForgotPasswordLink.Value = id;
                    cmd.Parameters.Add(spForgotPasswordLink);

                    cmd.Connection = cn;
                    using (da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds);
                    }
                    cn.Close();
                }
            }
        }
        return ds;
    }

    public bool Update_ResetPassword(string EmailID, string ForgotPasswordLink, string salt)
    {
        bool dataInserted = false;
        using (SqlCommand cmd = new SqlCommand("Reg.Update_ResetPassword"))
        {
            using (SqlConnection cn = ConnectionOpen())
            {
                cmd.Connection = cn;
                cmd.CommandTimeout = 0;
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter spEMailid = new SqlParameter("@Email", SqlDbType.VarChar);
                SqlParameter spForgotPasswordLink = new SqlParameter("@Password", SqlDbType.VarChar);
                SqlParameter spsalt = new SqlParameter("@salt", SqlDbType.VarChar);

                spEMailid.Value = EmailID;
                spForgotPasswordLink.Value = ForgotPasswordLink;
                spsalt.Value = salt;

                cmd.Parameters.Add(spEMailid);
                cmd.Parameters.Add(spForgotPasswordLink);
                cmd.Parameters.Add(spsalt);

                if (cmd.ExecuteNonQuery() > 0)
                    dataInserted = true;
            }
        }
        return dataInserted;
    }

    public DataSet GetUserID(int UserID)
    {
        DataSet ds = null;
        using (ds = new DataSet())
        {
            using (cmd = new SqlCommand("[Reg].[Select_UserID]"))
            {
                using (SqlConnection cn = ConnectionOpen())
                {
                    cmd.Connection = cn;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandTimeout = 0;

                    SqlParameter sUserID = new SqlParameter("@UserID", SqlDbType.Int);
                    sUserID.Value = UserID;
                    cmd.Parameters.Add(sUserID);


                    using (da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds);
                    }
                }
            }
        }
        return ds;
    }

    public void InviteUsers(int UserID,string Name,string ReferEmail,int ReferUserTypeID)
    {
        using (cmd = new SqlCommand("Reg.Insert_ReferredUser"))
        {
            using (SqlConnection cn = ConnectionOpen())
            {
                cmd.Connection = cn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandTimeout = 0;

                SqlParameter sUserID = new SqlParameter("@UserID", SqlDbType.Int);
                sUserID.Value = UserID;
                cmd.Parameters.Add(sUserID);


                SqlParameter sFName = new SqlParameter("@FirstName", SqlDbType.VarChar);
                sFName.Value = Name;
                cmd.Parameters.Add(sFName);

                SqlParameter sEmail = new SqlParameter("@Email", SqlDbType.VarChar);
                sEmail.Value = ReferEmail;
                cmd.Parameters.Add(sEmail);


                SqlParameter sUserTypeID = new SqlParameter("@UserTypeID", SqlDbType.Int);
                sUserTypeID.Value = ReferUserTypeID;
                cmd.Parameters.Add(sUserTypeID);

                cmd.ExecuteNonQuery();
            }
        }
    }

    public bool CheckReferred_Email(string Email)
    {
        SqlConnection cn = ConnectionOpen();
        cmd = new SqlCommand("Reg.CheckReferred_Email", cn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandTimeout = 0;
        cmd.Connection = cn;

        SqlParameter sEMailID = new SqlParameter("@Email", SqlDbType.VarChar);
        sEMailID.Value = Email;
        cmd.Parameters.Add(sEMailID);

        rd = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        if (rd.HasRows)
        {
            if (rd.Read())
            {
                if (rd["regEmail"] != DBNull.Value)
                {
                    if (rd["regEmail"].ToString() == Email)
                    {
                        rd.Close();
                        return true;

                    }
                }
                if (rd["invEmail"] != DBNull.Value)
                {
                    if (rd["invEmail"].ToString() == Email)
                    {
                        rd.Close();
                        return true;

                    }
                }
            }
        }

        rd.Close();
        return false ;
    }

    public DataSet Select_FilteredUser(int UserTypeID, string ValidTo, string ValidFrom)
    {
        DataSet ds = new DataSet();
        using (SqlCommand cmd = new SqlCommand("Reg.Select_FilteredUser"))
        {
            using (SqlConnection cn = ConnectionOpen())
            {
                cmd.Connection = cn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandTimeout = 0;

                SqlParameter sFName = new SqlParameter("@FirstName", SqlDbType.VarChar);
                SqlParameter sLName = new SqlParameter("@LastName", SqlDbType.VarChar); 
                SqlParameter sEmail = new SqlParameter("@Email", SqlDbType.VarChar); 

                sFName.Value = this.FirstName;
                sLName.Value = this.LastName; 
                sEmail.Value = this.Email; 

                cmd.Parameters.Add(sFName);
                cmd.Parameters.Add(sLName);
                cmd.Parameters.Add(sEmail);

                SqlParameter sUserTypeID = new SqlParameter("@UserTypeID", SqlDbType.Int);
                sUserTypeID.Value = UserTypeID;
                cmd.Parameters.Add(sUserTypeID);

                SqlParameter sValidTo = new SqlParameter("@ValidTo", SqlDbType.VarChar);
                sValidTo.Value = ValidTo;
                cmd.Parameters.Add(sValidTo);


                SqlParameter sValidFrom = new SqlParameter("@ValidFrom", SqlDbType.VarChar);
                sValidFrom.Value = ValidFrom;
                cmd.Parameters.Add(sValidFrom);
                using (da = new SqlDataAdapter(cmd))
                {
                    da.Fill(ds);
                }
            }
        }
        return ds;
    }

    public int UpdateAccount()
    {
        int activatedAccount = 0;
        using (cmd = new SqlCommand("Reg.Update_ActivatedbyEmail"))
        {
            using (SqlConnection cn = ConnectionOpen())
            {

                cmd.Connection = cn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandTimeout = 0;
                SqlParameter spUserID = new SqlParameter("@UserID", SqlDbType.Int);
                spUserID.Value = this.UserID;
                cmd.Parameters.Add(spUserID);
                activatedAccount = cmd.ExecuteNonQuery();
                cn.Close();
            }
        }
        return activatedAccount;
    }

    public SqlDataReader checkIFAccountUpdated()
    {
        SqlConnection cn = ConnectionOpen();
        cmd = new SqlCommand("Reg.check_AccountUpdated", cn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandTimeout = 0;
        cmd.Connection = cn;
        SqlParameter spUserID = new SqlParameter("@UserID", SqlDbType.Int);
        spUserID.Value = this.UserID;
        cmd.Parameters.Add(spUserID);
        rd = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        return rd;
    }


}
